/* global window */
import modelExtend from 'dva-model-extend'
import queryString from 'query-string'
import { message } from 'antd'
import { query, add, update, remove, config } from 'services/role'
import { queryNode } from 'services/common'
import { pageModel } from './common'

export default modelExtend(pageModel, {
  namespace: 'role',

  state: {
    list: [],
    nodes: [],
    currentItem: {},
    modalVisible: false,
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      dispatch({ type: 'queryData' })
      history.listen((location) => {
        if (location.pathname === '/role') {
          dispatch({
            type: 'query',
          })
        }
      })
    },
  },

  effects: {

    * queryData ({ payload = {} }, { call, put, select }) {
      const { nodes } = yield select(_ => _.role)
      console.log(nodes)
      if (nodes.length === 0) {
        const resData = yield call(queryNode, {})
        yield put({ type: 'updateState', payload: { nodes: resData.data } })
      }
    },

    * query ({ payload = {} }, { call, put }) {
      const { success, data, errorMsg } = yield call(query, payload)
      if (success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data,
          },
        })
      } else {
        throw errorMsg
      }
    },

    * delete ({ payload }, { call, put }) {
      const data = yield call(remove, payload)
      if (data.success) {
        yield put({ type: 'query' })
        message.success('删除成功')
      } else {
        throw data.errorMsg
      }
    },

    * save ({ payload }, { call, put }) {
      let data = {}
      if (payload.id) {
        data = yield call(update, payload)
      } else {
        data = yield call(add, payload)
      }
      if (data.success) {
        yield put({ type: 'hideModal' })
        yield put({ type: 'query' })
        message.success('保存成功')
      } else {
        throw data.errorMsg
      }
    },
  },

  reducers: {

    showModal (state, { payload }) {
      return { ...state, ...payload, modalVisible: true }
    },

    hideModal (state) {
      return { ...state, modalVisible: false }
    },

    showResetModal (state, { payload }) {
      return { ...state, ...payload, resetModalVisible: true }
    },

    hideResetModal (state) {
      return { ...state, resetModalVisible: false }
    },
  },
})
